#include "seer_status_provider.h"

#include <QDateTime>
#include <QHostAddress>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

#include "kernel/agv/agv_entity.h"

namespace {

using kernel::agv::NavStatus;

NavStatus convertSeerTaskStatus(int seerStatus) {
  switch (seerStatus) {
    case 0:
      return NavStatus::None;
    case 1:
      return NavStatus::Waiting;
    case 2:
      return NavStatus::Running;
    case 3:
      return NavStatus::Suspended;
    case 4:
      return NavStatus::Completed;
    case 5:
      return NavStatus::Failed;
    case 6:
      return NavStatus::Canceled;
    default:
      return NavStatus::None;  // fallback keeps dispatcher logic stable
  }
}

}  // namespace

namespace infrastructure {
namespace vehicle {
namespace seer {

SeerStatusProvider::SeerStatusProvider(int agvNumber, const QString &agvIp,
                                       quint16 agvPort, int pollInterval,
                                       int detailPollRatio,  // ← 添加这个参数
                                       std::shared_ptr<kernel::ILogger> logger,
                                       QObject *parent)
    : QObject(parent),
      m_agvNumber(agvNumber),
      m_agvIp(agvIp),
      m_agvPort(agvPort),
      m_pollInterval(pollInterval),
      m_detailPollRatio(detailPollRatio)  // ← 添加初始化
      ,
      m_logger(logger) {
  m_pollTimer = std::make_unique<QTimer>(this);
  connect(m_pollTimer.get(), &QTimer::timeout, this,
          &SeerStatusProvider::onPollTimer);
}

SeerStatusProvider::~SeerStatusProvider() { stop(); }

kernel::Result<void> SeerStatusProvider::start() {
  if (m_isRunning) {
    return kernel::Result<void>::success();
  }

  // 修改日志输出，添加计数器重置
  m_logger->info(QString("  - 基础轮询间隔: %1ms").arg(m_pollInterval));
  m_logger->info(QString("  - 详细数据比例: 1:%1").arg(m_detailPollRatio));
  // 初始化连接
  if (!initializeConnection()) {
    m_logger->error(QString("AGV %1 初始化连接失败").arg(m_agvNumber));
    return kernel::Result<void>::failure(kernel::ErrorCode::NetworkError,
                                         "Failed to initialize connection");
  }

  // 启动定时器
  m_pollTimer->start(m_pollInterval);
  m_isRunning = true;

  m_logger->info(QString("AGV %1 SEER StatusProvider 已启动").arg(m_agvNumber));

  return kernel::Result<void>::success();
}

void SeerStatusProvider::stop() {
  if (!m_isRunning) {
    return;
  }

  m_logger->info(
      QString("停止 SEER StatusProvider for AGV %1").arg(m_agvNumber));

  m_pollTimer->stop();

  if (m_robotStatus) {
    m_robotStatus.reset();
  }

  m_isConnected = false;
  m_isRunning = false;
}

bool SeerStatusProvider::isRunning() const { return m_isRunning; }

void SeerStatusProvider::setStatusUpdateCallback(
    StatusUpdateCallback callback) {
  m_statusCallback = callback;
}

int SeerStatusProvider::getAgvNumber() const { return m_agvNumber; }

bool SeerStatusProvider::initializeConnection() {
  // 创建 RobotStatus 实例
  m_robotStatus = std::make_unique<robokit::RobotStatus>();

  // 设置连接参数
  m_robotStatus->setDefaultAddress(m_agvIp);
  m_robotStatus->setDefaultTcpPort(m_agvPort);

  // 连接信号 - 接收解析后的完整状态数据
  connect(m_robotStatus.get(), &robokit::RobotStatus::statusAll1Updated, this,
          &SeerStatusProvider::onStatusReceived);

  // 初始化连接
  bool connected = m_robotStatus->initConnection();

  if (!connected) {
    m_logger->error(QString("AGV %1 RobotStatus 连接失败: %2:%3")
                        .arg(m_agvNumber)
                        .arg(m_agvIp)
                        .arg(m_agvPort));
    return false;
  }

  m_isConnected = true;
  m_logger->info(QString("AGV %1 RobotStatus 连接成功: %2:%3")
                     .arg(m_agvNumber)
                     .arg(m_agvIp)
                     .arg(m_agvPort));

  return true;
}

void SeerStatusProvider::onPollTimer() {
  if (!m_isConnected) {
    m_logger->warning(QString("AGV %1 未连接，尝试重新连接").arg(m_agvNumber));
    if (!initializeConnection()) {
      return;
    }
  }

  // 直接请求完整状态（robot_status_all1）
  requestStatus();
}

void SeerStatusProvider::requestStatus() {
  if (!m_robotStatus || !m_isConnected) {
    m_logger->warning(
        QString("AGV %1 RobotStatus未初始化或未连接").arg(m_agvNumber));
    return;
  }

  // 使用 RobotStatus API 请求完整状态（1100 命令 - robot_status_all1）
  m_robotStatus->robot_status_all1_req_get();
}

void SeerStatusProvider::onStatusReceived(
    const robokit::RobotStatusAll1Data &data) {
  // 直接使用解析好的完整状态数据，无需再次解析 JSON
  m_statusData = data;
  notifyStatusUpdate();
}

// 以下旧的解析函数已不再需要，由信号处理替代
/*
void SeerStatusProvider::updateCoreStatus(const QJsonObject &jsonObj) {
  // ========== 运行模式和位置 ==========
  m_coreStatus.mode = jsonObj.value("mode").toInt();
  m_coreStatus.x = jsonObj.value("x").toDouble();
  m_coreStatus.y = jsonObj.value("y").toDouble();
  m_coreStatus.angle = jsonObj.value("angle").toDouble();
  m_coreStatus.confidence = jsonObj.value("confidence").toDouble();
  m_coreStatus.currentStation = jsonObj.value("current_station").toString();
  m_coreStatus.lastStation = jsonObj.value("last_station").toString();

  // ========== 速度信息 ==========
  m_coreStatus.vx = jsonObj.value("vx").toDouble();
  m_coreStatus.vy = jsonObj.value("vy").toDouble();
  m_coreStatus.w = jsonObj.value("w").toDouble();
  m_coreStatus.steer = jsonObj.value("steer").toDouble();
  m_coreStatus.spin = jsonObj.value("spin").toDouble();

  // ========== 接收速度 ==========
  m_coreStatus.r_vx = jsonObj.value("r_vx").toDouble();
  m_coreStatus.r_vy = jsonObj.value("r_vy").toDouble();
  m_coreStatus.r_w = jsonObj.value("r_w").toDouble();
  m_coreStatus.r_steer = jsonObj.value("r_steer").toDouble();
  m_coreStatus.r_spin = jsonObj.value("r_spin").toDouble();

  // ========== 阻挡和减速 ==========
  m_coreStatus.isStop = jsonObj.value("is_stop").toBool();
  m_coreStatus.blocked = jsonObj.value("blocked").toBool();
  m_coreStatus.blockReason = jsonObj.value("block_reason").toInt();
  m_coreStatus.blockX = jsonObj.value("block_x").toDouble();
  m_coreStatus.blockY = jsonObj.value("block_y").toDouble();
  m_coreStatus.blockUltrasonicId = jsonObj.value("block_ultrasonic_id").toInt();
  m_coreStatus.blockDi = jsonObj.value("block_di").toInt();

  m_coreStatus.slowed = jsonObj.value("slowed").toBool();
  m_coreStatus.slowReason = jsonObj.value("slow_reason").toInt();
  m_coreStatus.slowX = jsonObj.value("slow_x").toDouble();
  m_coreStatus.slowY = jsonObj.value("slow_y").toDouble();
  m_coreStatus.slowUltrasonicId = jsonObj.value("slow_ultrasonic_id").toInt();
  m_coreStatus.slowDi = jsonObj.value("slow_di").toInt();

  // ========== 区域和路径 ==========
  m_coreStatus.areaIds.clear();
  QJsonArray areaIds = jsonObj.value("area_ids").toArray();
  for (const auto &areaId : areaIds) {
    m_coreStatus.areaIds.append(areaId.toString());
  }
  m_coreStatus.path = jsonObj.value("path").toArray();

  // ========== 急停和传感器 ==========
  m_coreStatus.emergency = jsonObj.value("emergency").toBool();
  m_coreStatus.driverEmc = jsonObj.value("driver_emc").toBool();

  // 解析DI数据
  m_coreStatus.digitalInputs.clear();
  QJsonArray diArray = jsonObj.value("DI").toArray();
  for (const auto &diValue : diArray) {
    QJsonObject diObj = diValue.toObject();
    kernel::dtos::SensorIO di;
    di.id = diObj.value("id").toInt();
    di.source = diObj.value("source").toString();
    di.status = diObj.value("status").toBool();
    di.valid = diObj.value("valid").toBool();
    m_coreStatus.digitalInputs.append(di);
  }

  // 解析DO数据
  m_coreStatus.digitalOutputs.clear();
  QJsonArray doArray = jsonObj.value("DO").toArray();
  for (const auto &doValue : doArray) {
    QJsonObject doObj = doValue.toObject();
    kernel::dtos::SensorIO doItem;
    doItem.id = doObj.value("id").toInt();
    doItem.source = doObj.value("source").toString();
    doItem.status = doObj.value("status").toBool();
    doItem.valid = true;  // DO没有valid字段，默认true
    m_coreStatus.digitalOutputs.append(doItem);
  }

  // ========== 姿态信息 ==========
  m_coreStatus.yaw = jsonObj.value("yaw").toDouble();
  m_coreStatus.roll = jsonObj.value("roll").toDouble();
  m_coreStatus.pitch = jsonObj.value("pitch").toDouble();

  // ========== 任务信息 ==========
  m_coreStatus.taskStatus = jsonObj.value("task_status").toInt();
  m_coreStatus.taskType = jsonObj.value("task_type").toInt();
  m_coreStatus.targetId = jsonObj.value("target_id").toString();
  m_coreStatus.targetPoint = jsonObj.value("target_point").toArray();

  // 未完成路径
  m_coreStatus.unfinishedPath.clear();
  QJsonArray unfinishedPath = jsonObj.value("unfinished_path").toArray();
  for (const auto &station : unfinishedPath) {
    m_coreStatus.unfinishedPath.append(station.toString());
  }

  // 已完成路径
  m_coreStatus.finishedPath.clear();
  QJsonArray finishedPath = jsonObj.value("finished_path").toArray();
  for (const auto &station : finishedPath) {
    m_coreStatus.finishedPath.append(station.toString());
  }

  // ========== 传感器详细数据 ==========
  m_coreStatus.ultrasonicNodes = jsonObj.value("ultrasonic_nodes").toArray();
  m_coreStatus.pgvs = jsonObj.value("pgvs").toArray();
  m_coreStatus.lasers = jsonObj.value("lasers").toArray();

  // ========== 错误和报警 ==========
  m_coreStatus.fatals = jsonObj.value("fatals").toArray();
  m_coreStatus.errors = jsonObj.value("errors").toArray();
  m_coreStatus.warnings = jsonObj.value("warnings").toArray();
  m_coreStatus.notices = jsonObj.value("notices").toArray();

  // ========== API信息 ==========
  m_coreStatus.retCode = jsonObj.value("ret_code").toInt();
  m_coreStatus.createOn = jsonObj.value("create_on").toString();
  m_coreStatus.errMsg = jsonObj.value("err_msg").toString();
  m_coreStatus.uploadTime = QDateTime::currentDateTime();
}
*/

/*
void SeerStatusProvider::updateDetailStatus(const QJsonObject &jsonObj) {
  // ========== 里程信息 ==========
  m_detailStatus.odo = jsonObj.value("odo").toDouble();
  m_detailStatus.todayOdo = jsonObj.value("today_odo").toDouble();

  // ========== 运行时间 ==========
  m_detailStatus.runTime = jsonObj.value("time").toDouble();
  m_detailStatus.totalRunTime = jsonObj.value("total_time").toDouble();

  // ========== 控制器状态 ==========
  m_detailStatus.controllerTemp = jsonObj.value("controller_temp").toDouble();
  m_detailStatus.controllerHumi = jsonObj.value("controller_humi").toDouble();
  m_detailStatus.controllerVoltage =
      jsonObj.value("controller_voltage").toDouble();

  // ========== 电池信息 ==========
  m_detailStatus.batteryLevel = jsonObj.value("battery_level").toDouble();
  m_detailStatus.batteryTemp = jsonObj.value("battery_temp").toDouble();
  m_detailStatus.charging = jsonObj.value("charging").toBool();
  m_detailStatus.voltage = jsonObj.value("voltage").toDouble();
  m_detailStatus.current = jsonObj.value("current").toDouble();
  m_detailStatus.maxChargeVoltage =
      jsonObj.value("max_charge_voltage").toDouble();
  m_detailStatus.maxChargeCurrent =
      jsonObj.value("max_charge_current").toDouble();
  m_detailStatus.manualCharge = jsonObj.value("manual_charge").toBool();
  m_detailStatus.autoCharge = jsonObj.value("auto_charge").toBool();
  m_detailStatus.batteryCycle = jsonObj.value("battery_cycle").toDouble();

  // ========== 系统状态 ==========
  m_detailStatus.relocStatus = jsonObj.value("reloc_status").toInt();
  m_detailStatus.loadmapStatus = jsonObj.value("loadmap_status").toInt();
  m_detailStatus.slamStatus = jsonObj.value("slam_status").toInt();

  // ========== API信息 ==========
  m_detailStatus.retCode = jsonObj.value("ret_code").toInt();
  m_detailStatus.createOn = jsonObj.value("create_on").toString();
  m_detailStatus.errMsg = jsonObj.value("err_msg").toString();
  m_detailStatus.uploadTime = QDateTime::currentDateTime();
}
*/

void SeerStatusProvider::notifyStatusUpdate() {
  if (!m_statusCallback) {
    return;
  }

  // 从 m_statusData 构造统一的 AgvStatusDTO
  kernel::dtos::AgvStatusDTO status;

  // ========== 基本信息 ==========
  status.agvNumber = m_agvNumber;
  status.ip = m_agvIp;

  // ========== 运行模式和位置 ==========
  status.mode = m_statusData.mode;
  status.x = m_statusData.x;
  status.y = m_statusData.y;
  status.angle = m_statusData.angle;
  status.confidence = m_statusData.confidence;
  status.currentStation = m_statusData.currentStation;
  status.lastStation = m_statusData.lastStation;

  // ========== 电池信息 ==========
  status.batteryLevel = m_statusData.batteryLevel*100;
  status.charging = m_statusData.charging;

  // ========== 地图信息 ==========
  status.current_map = m_statusData.current_map;
  // ========== 速度信息 ==========
  status.vx = m_statusData.vx;
  status.vy = m_statusData.vy;
  status.w = m_statusData.w;
  status.steer = m_statusData.steer;
  status.spin = m_statusData.spin;

  // ========== 阻挡和减速 ==========
  status.isStop = m_statusData.isStop;
  status.blocked = m_statusData.blocked;
  status.blockReason = m_statusData.blockReason;

  // ========== 区域和路径 ==========
  status.areaIds = m_statusData.areaIds;
  status.path = m_statusData.path;

  // ========== 急停和传感器 ==========
  status.emergency = m_statusData.emergency;
  status.driverEmc = m_statusData.driverEmc;
  // TODO: 需要将 QJsonArray 转换为 QList<SensorIO>
  // status.digitalInputs = m_statusData.digitalInputs;
  // status.digitalOutputs = m_statusData.digitalOutputs;

  // ========== 姿态 ==========
  status.yaw = m_statusData.yaw;
  status.roll = m_statusData.roll;
  status.pitch = m_statusData.pitch;

  // ========== 任务信息 ==========
  status.taskStatus = static_cast<int>(convertSeerTaskStatus(m_statusData.taskStatus));
  status.taskType = m_statusData.taskType;
  status.targetId = m_statusData.targetId;
  status.targetPoint = m_statusData.targetPoint;
  status.unfinishedPath = m_statusData.unfinishedPath;
  status.finishedPath = m_statusData.finishedPath;

  // 回调通知上层
  m_statusCallback(status);
}

}  // namespace seer
}  // namespace vehicle
}  // namespace infrastructure
